package com.mall.global.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
public class Log {
    private Logger logger = LoggerFactory.getLogger(Log.class);
    private String success = "success";
    private String fail = "fail";


    /**
     * @Description: 定义需要拦截的切面
     * @Pointcut("execution(* com.*.controller.*Controller.*(..))")
     * @Return: void
     **/
    @Pointcut("execution (* com.mall..*.*(..))")
    public void controllerPointcut() {

    }

    // 前置通知
    //@Before("controllerPointcut()")
    public void before() {
        logger.info("before() - 前置通知");
    }

    // 后置通知
    //@After("controllerPointcut()")
    public void after() {
        logger.info("after() - 后置通知");
    }

    // 环绕通知
    @Around("controllerPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        logger.info("around() - 环绕通知");
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("参数获取失败: {}", e.getMessage());
        }
        //最后返回
        return point.proceed();
    }

    // 异常通知
    @AfterThrowing(value = "controllerPointcut()", throwing = "tw")
    public void exp(Throwable tw) {
        logger.info("exp() - 异常通知");
        System.out.println(tw.getMessage());
    }

}

